<template>
  <div class="resources-view">
    <!-- 统一导航栏 -->
    <NavBar @toggle-sidebar="toggleSidebar" />
    
    <div class="resources-container">
      <!-- 侧边栏保持不变 -->
      <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <!-- 头部 -->
      <div class="sidebar-header">
        <h1 class="title">资源管理系统</h1>
        <p class="subtitle">教师端</p>
      </div>

      <!-- 导航 -->
      <div class="nav-menu">
        <button class="nav-item active" @click="gotoQuestions">习题管理</button>
        <button class="nav-item" @click="publishResource">发布资源</button>
      </div>

      <!-- 已选择统计 -->
      <div class="selected-stats">
        <div class="stats-card">
          <h3>已选择资源数量</h3>
          <div class="count">{{ selectedResourcesCount }}</div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 顶部栏简化，只保留标题 -->
      <div class="top-bar">
        <h2>教学资源库</h2>
        <button
            class="generate-btn"
            @click="backToHome"
        >
          返回
        </button>
      </div>

      <!-- 搜索和筛选栏 -->
      <div class="filter-bar">
        <div class="filter-group">
          <label>类型：</label>
          <el-select v-model="selectedType" placeholder="全部" class="filter-select">
            <el-option v-for="type in typeOptions" :key="type" :label="type" :value="type" />
          </el-select>
        </div>


        <div class="search-group">
          <el-input
              v-model="searchKeyword"
              placeholder="搜索资源名称..."
              @input="searchResources"
              style="width: 300px"
          >
            <template #append>
              <el-button @click="searchResources">搜索</el-button>
            </template>
          </el-input>
        </div>

        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 全选栏 -->
      <div class="select-all-bar">
        <el-checkbox v-model="selectAll" @change="toggleSelectAll">全选</el-checkbox>
        <span class="total-count">共 {{ totalResourcesCount }} 个资源</span>
      </div>

      <!-- 资源列表 -->
      <div class="resources-list">
        <div
            v-for="resource in filteredResources"
            :key="resource.id"
            class="resource-card"
        >
          <el-checkbox
              :model-value="selectedResources.includes(resource.id)"
              @change="toggleResourceSelection(resource.id)"
          />

          <div class="resource-icon">
            <el-icon v-if="resource.type === '文档'"><Document /></el-icon>
            <el-icon v-else-if="resource.type === '视频'"><VideoCamera /></el-icon>
            <el-icon v-else-if="resource.type === '图片'"><Picture /></el-icon>
            <el-icon v-else-if="resource.type === '语音'"><Microphone /></el-icon>
            <el-icon v-else><FolderOpened /></el-icon>
          </div>

          <div class="resource-info">
            <div class="resource-name">{{ resource.name }}</div>

            <div class="resource-tags">
        <span
            class="type-tag"
            :style="{ background: resource.typeColor, color: resource.typeTextColor }"
        >
          {{ resource.type }}
        </span>
            </div>

            <div class="resource-meta">
              <span>创建: {{ resource.createDate }}</span>
            </div>

            <div class="resource-actions">
              <el-button size="small" @click="previewResource(resource.ossUrl)">预览</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  //预览框
  <el-dialog
      v-model="previewVisible"
      title="资源预览"
      width="80%"
      top="5vh"
      :before-close="handlePreviewClose"
      class="custom-preview-dialog"
  >
    <template v-if="previewUrl">
      <!-- 图片 -->
      <img
          v-if="isImage(previewUrl)"
          :src="previewUrl"
          alt="预览图片"
          class="image-preview"
      />

      <!-- PDF / Office -->
      <!-- 视频 -->
      <video
          v-else-if="isVideo(previewUrl)"
          :src="previewUrl"
          controls
          class="media-preview"
      />

      <!-- 音频 -->
      <audio
          v-else-if="isAudio(previewUrl)"
          :src="previewUrl"
          controls
          class="audio-preview"
      />

      <!-- Office 文档 -->

      <!-- 其他（不支持的格式） -->
      <div v-else class="unsupported-box">
        <p>该文件格式暂不支持预览</p>
        <el-button type="primary" @click="downloadResource(previewUrl)">下载资源</el-button>
      </div>
    </template>
  </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted} from 'vue'
import { useRouter } from 'vue-router';
import { getAiResourcesListAPI, selectResourcesAPI} from '@/apis/index.ts'
import {ElMessage, ElMessageBox} from "element-plus";
import { Document, VideoCamera, Picture, Microphone,FolderOpened } from '@element-plus/icons-vue'
import NavBar from '@/components/NavBar.vue'

// 侧边栏状态
const sidebarCollapsed = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

interface Resource {
  resourceId: number
  chatId: number
  userId: number
  ossUrl: string
  type: string
  createdAt: string
  title:string
}
// UI 展示用的封装后的资源类型
interface DisplayResource {
  id: number
  name: string
  ossUrl: string
  type: string
  typeColor: string
  typeTextColor: string
  createDate: string
}

const resources = ref<DisplayResource[]>([])

const router = useRouter()

const activeTab = ref('myResources')
const selectAll = ref(false)
const selectedResources = ref<number[]>([])
const searchKeyword = ref('')
const selectedType = ref('全部')
const selectedStatus = ref('全部')

const typeOptions = ['全部', '文档', '视频', '图片','语音']

//获取资源列表
const fetchResources = async () => {
  try {
    const userId = Number(localStorage.getItem('id')||1)
    const res = await getAiResourcesListAPI(userId)
    if (res.code === 200 && Array.isArray(res.data)) {
      resources.value = res.data.map((item): DisplayResource => {
        const typeColorMap = {
          文档: '#E0E7FF',
          视频: '#FEF3C7',
          图片: '#c5ffe6',
          语音: '#F3F4F6'
        }
        const typeTextColorMap = {
          文档: '#3730A3',
          视频: '#92400E',
          图片: '#12451d',
          语音: '#111827'
        }

        let createDate = '未知'
        if (typeof item.createdAt === 'string') {
          createDate = item.createdAt.slice(0, 10)
        } else if (item.createdAt && typeof item.createdAt === 'object') {
          const date = new Date(item.createdAt as any)
          if (!isNaN(date.getTime())) {
            createDate = date.toISOString().slice(0, 10)
          }
        }

        return {
          id: item.resourceId,
          name: item.title,
          ossUrl: item.ossUrl,
          type: item.type,
          typeColor: typeColorMap[item.type as keyof typeof typeColorMap] || '#E5E7EB',
          typeTextColor: typeTextColorMap[item.type as keyof typeof typeTextColorMap] || '#374151',
          createDate
        }
      })
    }
  } catch (err) {
    console.error('资源列表获取失败:', err)
  }
}

onMounted(() => {
  fetchResources()
})
const backToHome = () => {
  router.push('/teacher-home')
}
//资源预览
const previewVisible = ref(false)
const previewUrl = ref('')

// 调用此方法打开预览框
const previewResource = (ossUrl: string) => {
  previewUrl.value = ossUrl
  previewVisible.value = true
}

// 关闭弹窗时清理
const handlePreviewClose = () => {
  previewVisible.value = false
  previewUrl.value = ''
}

// 工具函数
const isImage = (url: string) => /\.(png|jpe?g|gif|bmp|webp)$/i.test(url)
const isPDF = (url: string) => /\.pdf$/i.test(url)
const isVideo = (url: string) => /\.(mp4|webm|ogg)$/i.test(url)
const isAudio = (url: string) => /\.(mp3|wav|ogg|aac)$/i.test(url)
const isOfficeDoc = (url: string) => /\.(docx|pptx|xlsx)$/i.test(url)
const getOfficeViewerUrl = (url: string) =>
    `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(url)}`

// 触发浏览器下载
const downloadResource = (url: string) => {
  if (!url) return
  // 创建一个隐藏的 a 标签，模拟点击实现下载
  const link = document.createElement('a')
  link.href = url
  // 提取文件名（可根据实际url调整）
  const urlParts = url.split('/')
  const filename = urlParts[urlParts.length - 1] || 'resource'
  link.download = decodeURIComponent(filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 计算属性：过滤后的资源列表
const filteredResources = computed(() => {
  let list = resources.value
  if (selectedType.value !== '全部') {
    list = list.filter(r => r.type === selectedType.value)
  }
  if (searchKeyword.value) {
    list = list.filter(r => r.name.includes(searchKeyword.value))
  }
  return list
})

const selectedResourcesCount = computed(() => selectedResources.value.length)
const totalResourcesCount = computed(() => resources.value.length)

const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedResources.value = filteredResources.value.map(r => r.id)
  } else {
    selectedResources.value = []
  }
}

const toggleResourceSelection = (resourceId: number) => {
  const index = selectedResources.value.indexOf(resourceId)
  if (index > -1) {
    selectedResources.value.splice(index, 1)
  } else {
    selectedResources.value.push(resourceId)
  }
  selectAll.value = filteredResources.value.length > 0 &&
      filteredResources.value.every(r => selectedResources.value.includes(r.id))
}

const searchResources = () => {}
const resetFilters = () => {
  searchKeyword.value = ''
  selectedType.value = '全部'
  selectedStatus.value = '全部'
}


// 发布资源
const publishResource = async () => {
  const examId = Number(localStorage.getItem('examId')||1)
  if (selectedResources.value.length === 0) {
    ElMessage.warning('请先选择资源')
    return
  }

  try {
    const res = await selectResourcesAPI({
      examId,
      resourceIds: selectedResources.value
    })

    if (res.code === 200) {
      ElMessage.success('资源发布成功')

    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布异常：', error)
    ElMessage.error('请求失败')
  }
}

const gotoQuestions = () => {
  router.push('/questions')
}
</script>


<style scoped>
.resources-view {
  min-height: 100vh;
  background: linear-gradient(180deg, #E2E8F0 0%, #F8FAFC 100%);
  font-family: 'Inter', sans-serif;
}

.resources-container {
  display: flex;
  min-height: calc(100vh - 64px); /* 减去NavBar的高度64px */
  height: calc(100vh - 64px);
}

/* 侧边栏样式 - 与试卷系统保持一致 */
.sidebar {
  width: 280px;
  background: #F8F9FA;
  border-right: 1px solid #E5E7EB;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.sidebar.collapsed {
  width: 0;
  overflow: hidden;
}

.sidebar-header {
  padding: 24px;
  border-bottom: 1px solid #E5E7EB;
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #1F2937;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #6B7280;
  margin: 0;
}

.nav-menu {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.nav-item {
  width: 100%;
  height: 45px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.2s;
}

.nav-item.active {
  background: #000;
  color: white;
}

.nav-item:not(.active) {
  background: white;
  color: #6B7280;
  border: 1px solid #D9D9D9;
}

.nav-item:not(.active):hover {
  background: #F3F4F6;
}

.selected-stats {
  flex: 1;
  display: flex;
  align-items: end;
  padding: 16px;
  border-top: 1px solid #E5E7EB;
}

.stats-card {
  width: 100%;
  background: #E6F1FF;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.stats-card h3 {
  font-size: 20px;
  font-weight: 500;
  color: #1E40AF;
  margin: 0 0 20px 0;
}

.count {
  font-size: 32px;
  font-weight: 700;
  color: #1E40AF;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.top-bar {
  background: white;
  border-bottom: 1px solid #E5E7EB;
  padding: 25px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.top-bar h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1F2937;
  margin: 0;
}

.generate-btn {
  background: #F3F4F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 15px;
  font-weight: 500;
  color: #9CA3AF;
  cursor: pointer;
  transition: all 0.2s;
}

.generate-btn:not(:disabled) {
  background: #1F2937;
  color: white;
}

.generate-btn:not(:disabled):hover {
  background: #374151;
}


.filter-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-select {
  width: 120px;
}

.filter-bar {
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}


.total-count {
  font-size: 14px;
  color: #64748B;
}

/* 资源列表样式 */
.resources-list {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.resource-card {
  background: white;
  border: 1px solid #E5E7EB;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  transition: all 0.2s;
}

.resource-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.resource-icon {
  width: 80px;
  height: 60px;
  border-radius: 6px;
  background: #F1F5F9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: #4B5563;
}

.resource-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.resource-name {
  font-size: 16px;
  font-weight: 600;
  color: #1F2937;
}

.resource-tags {
  display: flex;
  gap: 8px;
}

.type-tag,
.status-tag {
  padding: 2px 10px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
}

.resource-meta {
  font-size: 13px;
  color: #64748B;
  display: flex;
  gap: 16px;
}

.resource-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}
.filter-bar {
  padding: 20px 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.search-group {
  flex: 1;
  max-width: 300px;
}

.select-all-bar {
  padding: 16px 24px;
  display: flex;
  align-items: center;
  gap: 12px;
  background: white;
  border-bottom: 1px solid #E5E7EB;
}

.total-count {
  font-size: 14px;
  color: #64748B;
}

/* Element Plus 样式覆盖 */
:deep(.el-select) {
  width: 120px;
}

:deep(.el-input) {
  width: 220px;
}

:deep(.el-button) {
  height: 38px;
}

/* 预览框样式 */
.custom-preview-dialog >>> .el-dialog__body {
  padding: 20px;
  background-color: #f9f9f9;
}

.media-preview {
  width: 100%;
  max-height: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.audio-preview {
  width: 100%;
  margin-top: 10px;
}

.unsupported-box {
  text-align: center;
  padding: 24px;
}

.unsupported-box p {
  margin-bottom: 16px;
  font-size: 16px;
  color: #666;
}
.image-preview {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: contain;
  margin: 0 auto;
}

</style>